<?php

namespace Home\Controller;
use Common\Controller\Base;
use Common\Model\Model;
use Think\Controller;

class TryController extends Base {

    //初始化
    protected function _initialize() {
        parent::_initialize();
        /*//当前导航
        $this->assign('trynav', $this->getTryNav());
        $this->cate=$this->tryCategory();
        //更新状态,把过期的产品更新为过期
        $arr['iffinish']=true;
        $map['end_time']=array('LT',time());
        M('TryItems')->where($map)->save($arr);
        $data['iffinish']=false;
        $where['end_time']=array('GT',time());
        M('TryItems')->where($where)->save($data);*/
        //右侧广告
        $this->rightad=parent::getAdvert(5,3,0,1);

    }

    //获取产品类型列表
    public function tryCategory(){
        $data=M('TryCategory')->field('catename,cateid,image')->where(array('status'=>true))->select();
        return $data;
    }

    //试用首页
    public function index(){

        //推荐产品
        $filed=array('tryid','title','image','requestnum','price','trynum','end_time');
        //$this->tjtry=M('TryItems')->field($filed)->where(array('status'=>true,'iftj'=>true,'iffinish'=>false))->order('sort DESC,tryid DESC')->limit(1)->find();

        $this->hottry=M('TryItems')->field($filed)->where(array('status'=>true,'ifhot'=>true,'iffinish'=>false))->limit(2)->select();
      
        $this->newesttry=M('TryItems')->field($filed)->where(array('status'=>true,'iftj'=>true,'iffinish'=>false))->order('sort DESC,tryid DESC')->limit(4)->select();

        $this->tryreport=M('TryReport')->field('tryid,image,id,content')->where(array('status'=>true))->limit(3)->select();

        $tryApply = M('TryApply')->alias('A')
                    ->field('U.openuid,U.uavatar,U.nickname,A.create_time,I.tryid,I.title')
                    ->join('__USER__ U ON U.userid = A.userid')
                    ->join('__TRY_ITEMS__ I ON I.tryid = A.tryid')
                    ->where(array('A.status'=>1))
                    ->order('A.create_time DESC')
                    ->limit(8)
                    ->select();
        
        $this->assign('tryApply',$tryApply);

        //中间广告位
        $this->assign('midad',parent::getAdvert(6,1,0,1));

        $this->display();

    }

    //最新试用
    public function newtry(){
        $where['iffinish']=array('EQ',false);
        $this->trylist($where);
        $this->display();
    }

    //往期试用
    public function lasttry(){
        $where['iffinish']=array('EQ',true);
        $this->trylist($where);
        $this->display();
    }

    //试用列表
    public function trylist($where){
        $worksModel=M('TryItems');
        $gets=I('get.');
        $where['status']=array('EQ',true);


        $count = $worksModel->where($where)->count();
        $page = $this->Pages($count, 8);
        $pageurl='?page='.urlencode('[PAGE]');
        

        $list=$worksModel
            ->where($where)
            ->field('title,tryid,image,requestnum,trynum,price,end_time')
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();

        $this->assign("list", $list);
        $this->assign("Page", $page->show());

         $tryApply = M('TryApply')->alias('A')
                    ->field('U.openuid,U.uavatar,U.nickname,A.create_time,I.tryid,I.title')
                    ->join('__USER__ U ON U.userid = A.userid')
                    ->join('__TRY_ITEMS__ I ON I.tryid = A.tryid')
                    ->where(array('A.status'=>1))
                    ->order('A.create_time DESC')
                    ->limit(6)
                    ->select();
        
        $this->assign('tryApply',$tryApply);

        //中间广告位
        $this->assign('midad',parent::getAdvert(6,1,0,1));
      
    }

    //详情页面
    public function detail(){
        $tryid=I('get.tryid');
        $report=I('get.report');
        $pass=I('get.pass');
        if(empty($tryid)){
            $this->error('您访问的页面不存在!');
        }
        //增加点击数
        M('TryItems')->where(array('tryid'=>$tryid))->setInc('clicknum');
        
        $result=M('TryItems')->where(array('status'=>true,'tryid'=>$tryid))->find();
        if($result){
            $result['rcount']=M('TryApply')->where(array('tryid'=>$tryid,'userid'=>$this->userid))->count();
            
            //计算时间
            if($result['end_time'] > time()){
                $second=$result['end_time'] - time();
                $day=floor($second/(3600*24));
                $second = $second%(3600*24);
                $hour = floor($second/3600);
                $second = $second%3600;
                $minute = floor($second/60);
                $second = $second%60;
                $result['end_time']= "<span>".$day."</span>天<span>".$hour."</span>小时<span>".$minute."</span>分";
            }
            
            
            $this->assign('data',$result);
        }else{
            $this->error('您访问的页面不存在!');
        }
       if($report==1){
           $this->act1='act';

           $where['tryid']=$tryid;
           $count = M('TryReport')->where($where)->count();
           $limitRows = 5; // 设置每页记录数
           $page = $this->ajaxpage($count,$limitRows,'#msg','ajax_div','ajax_page_div');
           $rpModel=new Model();
           $report=$rpModel
               ->table(array(
                       C('DB_PREFIX').'try_report'=>'R',
                       C('DB_PREFIX').'user'=>'U',
                   )
               )
               ->where('R.userid=U.userid and R.status=true and R.tryid='.$tryid.'')
               ->field('R.create_time,R.content,R.otherpic,R.image,R.title,R.id,U.nickname,U.uavatar,U.openuid')
               ->order('R.create_time DESC')
               ->limit($page->firstRow . ',' . $page->listRows)
               ->select();
           $content='<div class="nodata">还没有用户提交报告哦！赶快去申请试用写报告吧!</div>';
           foreach($report as $v){
               $otherpic=explode('|',$v['otherpic']);
               $content='<div class="report-item">';
               $content.='<ul class="uheader"><a href="'.WEB_URL.'/u/'.$v['openuid'].'"><img src="'.$v['uavatar'].'" /><p>'.$v['nickname'].'</p></a></ul>';

               $content.='<a target="_blank" href="'.WEB_URL.'/try/reportdetail/'.$v['id'].'.html"><ul class="info">';
               $content.='<li class="addtime">'.$v['title'].'<span>发布于: '.date('Y/m/d H:i:s',$v['create_time']).'</span></li>';
               $content.='<li class="otherpic"><img src="'.$v['image'].'"> ';
               if(!empty($otherpic)){
                   foreach ($otherpic as $key=>$vv) {
                       $content.='<img src='.IMAGES_URL.$vv.'>';
                   }
               }
               $content.='</li>';
               $content.='<li class="content">'.$v['content'].'</li>';

               $content.='</ul></a>';
               $content.='</div>';
           }


       }elseif($pass==1){
           $this->act2='act';
           $applylist=M('TryApply')->where(array('status'=>true,'tryid'=>$tryid))->select();
           foreach($applylist as $key=>$value){
               $userinfo[$key]=M('User')->field('uavatar,nickname,userid,openuid')->where(array('userid'=>$value['userid']))->find();
           }
            if(empty($applylist)){
                $content='<div class="nodata">暂无用户参与试用!</div>';
            }else{
                foreach($userinfo as $k=>$v){
                    $uavatar=IMAGES_URL.$v['uavatar'];
                    $uurl=WEB_URL.'/u/'.$v['openuid'];
                    $content.="<div class='pass-user'><a href='$uurl'><img src='$uavatar' /><p>$v[nickname]</p></a></div>";
                }
            }
       }else{
           $this->act='act';
           $content=$result['content'];
       }

        $this->content=$content;

        //其他试用产品
        $spLink = M('TryItems')->field('tryid,title,image,clicknum')->where(array('status'=>true))->limit(3)->select();
        $this->assign('spLink',$spLink);

        $this->display();
    }


    //申请试用操作
    public function apply(){
        $this->check(1);
        $get=I('get.');
        $get['userid']=$this->userid;
        $get['tryid']=$get['infoid'];
        unset($get['infoid']);
        $count=M('TryApply')->where(array('userid'=>$get['userid'],'tryid'=>$get['tryid']))->count();
        if($count){
            $this->error('<span>请已经申请过了,请耐心等待商家审批!</span><span><a class="btn" href="/user/index/trylist">查看申请的宝贝</a></span>');
        }
        $get['status']=false;
        $get['create_time']=time();
        $result=M('TryApply')->add($get);
        if($result){
            $data['requestnum'] = array('exp','requestnum+1');
        //    $data['lastnum'] = array('exp','lastnum-1');
            M('TryItems')->where(array('tryid'=>$get['tryid']))->save($data);
            $this->success('<span>申请提交成功,请耐心等待商家审批! </span><span><a class="btn" href="/user/index/trylist">查看申请的宝贝</a></span>');
        }else{
            $this->error('申请出错,请稍候再试!');
        }
    }


    //报名页面
    public function baoming(){
        if(IS_POST){
            $post=I('post.');
            if(empty($post['mshop']) || !strstr($post['mshop'],'http://')){
                $this->error('请填写您的店铺链接地址,地址必须带http://');
            }
            if(empty($post['mprovince'])){
                $this->error('请选择您所在地区');
            }
            if(empty($post['mname'])){
                $this->error('请填写联系人姓名');
            }
            if(empty($post['mtel'])){
                $this->error('请留下您的联系电话');
            }
            $post['create_time']=time();
            $post['status']=false;
            $model=M('TryMember');
            $result=$model->add($post);
            if($result){
                $this->success('您的信息已提交,我们会尽快与您联系!');
            }else{
                $this->error('信息提交失败,请稍候再试!');
            }
        }else{
            $this->province=getProvince();
            $this->display();
        }
    }

    //试用报告
    public function report(){
        $model=M('TryReport');
        $where['status']=array('EQ',true);
      

        $count = $model->where($where)->count();
        $page = $this->Pages($count, 8);
        $list=$model
            ->where($where)
            ->field('tryid,userid,id,image,content')
            ->order('id DESC')
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();

         $tryApply = M('TryApply')->alias('A')
                    ->field('U.openuid,U.uavatar,U.nickname,A.create_time,I.tryid,I.title')
                    ->join('__USER__ U ON U.userid = A.userid')
                    ->join('__TRY_ITEMS__ I ON I.tryid = A.tryid')
                    ->where(array('A.status'=>1))
                    ->order('A.create_time DESC')
                    ->limit(6)
                    ->select();
        
        $this->assign('tryApply',$tryApply);

        //中间广告位
        $this->assign('midad',parent::getAdvert(6,1,0,1));

        $this->assign("list", $list);
        $this->assign("Page", $page->show());

        $this->display();
    }


    public function reportdetail(){
        $aid=I('get.id');
        if(empty($aid)){
            $this->error('您访问的页面不存在!');
        }
        $data=M('TryReport')->where(array('status'=>true,'id'=>$aid))->find();
        $model=New Model();
        $data=$model->table(array(
                C('DB_PREFIX').'try_report'=>'R',
                C('DB_PREFIX').'try_items'=>'I',
                C('DB_PREFIX').'user'=>'U'
            ))
            ->where('I.tryid=R.tryid and U.userid=R.userid and R.status=true and R.id='.$aid)
            ->field('R.id,R.msgnum,I.title,I.price,I.buylink,U.openuid,U.uavatar,U.nickname,U.ifrz,R.create_time,R.content,R.image,R.otherpic')
            ->find();

        $data['otherpic']=explode('|',$data['otherpic']);
        if($data){
            $this->assign('data',$data);
        }else{
            $this->_empty();
        }

        //评论
        $where['infoid']=$aid;
        $where['type']=3;
        $where['parent_id'] = 0;
        $count = M('UserMessage')->where($where)->count();

       // $limitRows = 5; // 设置每页记录数
        $limitRows = C('YF_PAGE');
        $page = $this->ajaxpage($count,$limitRows,'#msg','ajax_div','ajax_page_div');

        $msgModel=new Model();
        $message=$msgModel
            ->table(array(
                    C('DB_PREFIX').'user_message'=>'M',
                    C('DB_PREFIX').'user'=>'U',
                )
            )
            ->where('M.userid=U.userid and M.status=true and M.infoid='.$aid.' and M.type=3 and M.parent_id=0')
            ->field('M.create_time,M.content,U.nickname,U.uavatar,U.openuid,U.uprovince,U.ucity,U.userid,M.id,M.touserid')
            ->order('M.create_time DESC')
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();

//         foreach($message as $k=>$v){
//             $message[$k]['touser']=M('User')->field('openuid,nickname')->where(array('userid'=>$v['touserid']))->find();
//         }
            foreach($message as $k=>$v)
            {
            	$child_temp = array();
            	$child_temp = $msgModel->table(C('DB_PREFIX').'user_message')->field('*')->where(array('parent_id' => $v['id']))->order('create_time ASC')->select();
            
            	$message[$k]['childlist'] = array();
            	if($child_temp)
            	{
            		foreach($child_temp as $yk => $yv)
            		{
            			if($yv['userid'] == 0)
            			{
            				$child_temp[$yk]['nickname'] = "烘焙圈";
            				$child_temp[$yk]['openuid'] = 0;
            			}
            			else
            			{
            				$yf_user = array();
            				$yf_user = M('User')->field('openuid, nickname, uprovince, ucity, uavatar, ifrz')->where(array('userid'=>$yv['userid']))->find();
            				$child_temp[$yk]['nickname'] = $yf_user['nickname'];
            				$child_temp[$yk]['openuid'] = $yf_user['openuid'];
            				$child_temp[$yk]['uprovince'] = $yf_user['uprovince'];
            				$child_temp[$yk]['ucity'] = $yf_user['ucity'];
            				$child_temp[$yk]['uavatar'] = $yf_user['uavatar'];
            				$child_temp[$yk]['ifrz'] = $yf_user['ifrz'];
            			}
            			if($yv['touserid'] != 0)
            			{
            				$child_temp[$yk]['touser'] = M('User')->field('openuid,nickname')->where(array('userid'=>$yv['touserid']))->find();
            			}
            			else
            			{
            				$child_temp[$yk]['touser']['nickname'] = "烘焙圈";
            				$child_temp[$yk]['touser']['openuid'] = 0;
            			}
            		}
            		$message[$k]['childlist'] = $child_temp;
            	}
            	$message[$k]['tempname'] = hy_substr($v['nickname'], 4, true);
            	//$message[$k]['tempname'] = $v['nickname'];
            	$message[$k]['touser'] = array();
            	if(!empty($v['touserid']))
            	{
            		$message[$k]['touser']=M('User')->field('openuid,nickname')->where(array('userid'=>$v['touserid']))->find();
            	}
            }
            unset($where['parent_id']);
            $this->msgcount=M('UserMessage')->where($where)->count();
        $this->msgtype=3;
        $this->assign('msglist',$message);
        $this->assign('page',$page->show());

        if(IS_AJAX){
            exit($this->fetch('msglist'));
        }

        $this->display();
    }

    //获取排序
    function getorder($str){
        switch ($str){
            case '1':
                $strs='tryid';
                break;
            case '2':
                $strs='price';
                break;
            case '3':
                $strs='clicknum';
                break;
            case '4':
                $strs='trynum';
                break;
            case '5':
                $strs='lastnum';
                break;
        }
        return $strs;
    }


}